package com.zzyl.nursing.service.impl;

import java.lang.reflect.Member;
import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.member.RestReservationCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import com.zzyl.framework.web.service.TokenService;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static cn.hutool.core.util.RandomUtil.randomInt;

/**
 * 老人家属Service业务层处理
 * 
 * @author lww
 * @date 2024-11-16
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    TokenService tokenService;
    private static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");
    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public LoginVo login(UserLoginRequestDto loginRequestDto) {

        //1.获取openid
        String openid = wechatService.getOpenid(loginRequestDto);
        //2.手机号，可能要更新
        String phone = wechatService.getPhone(loginRequestDto.getPhoneCode());

        //2.判断是否已有这个人,有的话就更新（不要更新别的字段，在并发情况下会导致修改了别人修改的字段，造成数据不一致)
        FamilyMember member = lambdaQuery().eq(FamilyMember::getOpenId, openid).one();

        if (Objects.isNull(member)) {

            member.setOpenId(openid);
            member.setPhone(phone);
            member.setName(DEFAULT_NICKNAME_PREFIX.get(randomInt(0,DEFAULT_NICKNAME_PREFIX.size()))+ StringUtils.substring(phone,7));
            this.save(member);
        }else{
            //如果电话号码修改了就更新
            if (!Objects.equals(member.getPhone(),phone)){
                lambdaUpdate().set(FamilyMember::getPhone,phone)
                        .eq(FamilyMember::getId,member.getId());
            }

        }
        //2.5 生成token, jwt 载荷
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", member.getId());
        claims.put("nickName", member.getName());
        // 生成token
        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    @Override
    public Integer getCancelledReservationCount(Long userId) {

        //todo
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        return familyMemberMapper.selectCancelledReservationCount(userId, startTime, endTime);

    }

    @Override
    public List<RestReservationCountVo> selectRestReservationCount(Long time) {
        LocalDateTime endDay = LocalDateTimeUtil.of(time);
        LocalDateTime nowDay = endDay.plusDays(1);
        List<RestReservationCountVo> restReservationCountVos =familyMemberMapper.selectRestReservationCount(nowDay,endDay);

        //剩余多少次预约
        restReservationCountVos.forEach(item->{
            item.setCount(6 - item.getCount());
        });
        return restReservationCountVos;
    }


}
